package com.yuncheng.spcyApi.controller;

import java.io.File;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.util.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.bean.BeanUtil;
import org.apache.commons.collections.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yuncheng.spcyApi.alog.annotation.Log;
import com.yuncheng.spcyApi.constant.common.BusinessConstant;
import com.yuncheng.spcyApi.constant.common.LogConstant;
import com.yuncheng.spcyApi.constant.common.SpcyConstant;
import com.yuncheng.spcyApi.service.ISpcyLogService;
import com.yuncheng.spcyApi.service.IYcSysUserService;
import com.yuncheng.spcyApi.utils.*;
import com.yuncheng.vo.CurrentUserVo;
import com.yuncheng.vo.HttpResult;
import com.yuncheng.common.base.controller.BaseController;
import com.yuncheng.spcyApi.entity.SysUserJlcfqk;
import com.yuncheng.spcyApi.service.ISysUserJlcfqkService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuncheng.spcyApi.vo.common.HttpResultVo;
import io.swagger.annotations.ApiImplicitParam;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.multipart.MultipartFile;
import utils.LogUtils;
import utils.ObjectToMapUtils;

/**
 * @Description: 系统-用户奖励惩罚情况
 * @Author: yuncheng
 * @Date: 2023-04-06
 * @Version: V1.0
 */
@Api(tags = "系统-用户奖励惩罚情况接口")
@RestController
@RequestMapping("/api/spzx-spcy/sysUserJlcfqk")
public class SysUserJlcfqkController extends BaseController<SysUserJlcfqk, ISysUserJlcfqkService> {

    private static final Logger log = LoggerFactory.getLogger(SysUserJlcfqkController.class);

    @Resource
    private ISysUserJlcfqkService sysUserJlcfqkService;

    @Resource
    private ISpcyLogService spcyLogService;

    @Resource
    private LocalFileUploadUtils localFileUploadUtils;

    @Resource
    private MyExcelUtils myExcelUtils;

    @Resource
    private IYcSysUserService ycSysUserService;

    @Log(title = "用户奖励惩罚情况-分页列表查询")
    @ApiOperation(value = "用户奖励惩罚情况-分页列表查询")
    @GetMapping(value = "/queryPageList")
    public HttpResult<?> queryPageList(SysUserJlcfqk sysUserJlcfqk,
                                       @RequestParam(value = "year",defaultValue = "")String year,
                                       @RequestParam(value = "isSelectMe",defaultValue = "true")boolean isSelectMe,
                                       @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<SysUserJlcfqk> page = new Page<>(pageNo, pageSize);
        LambdaQueryWrapper<SysUserJlcfqk> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(sysUserJlcfqk.getFuserid())){
            isSelectMe = false;
        }
        queryWrapper.eq(StringUtils.isNotBlank(sysUserJlcfqk.getFuserid()),SysUserJlcfqk::getFuserid,sysUserJlcfqk.getFuserid());
        queryWrapper.like(StringUtils.isNotEmpty(sysUserJlcfqk.getFbjyy()), SysUserJlcfqk::getFbjyy,sysUserJlcfqk.getFbjyy());
        queryWrapper.like(StringUtils.isNotEmpty(sysUserJlcfqk.getFlx()),SysUserJlcfqk::getFlx,sysUserJlcfqk.getFlx());
        queryWrapper.like(StringUtils.isNotEmpty(sysUserJlcfqk.getFmc()),SysUserJlcfqk::getFmc,sysUserJlcfqk.getFmc());
        queryWrapper.like(StringUtils.isNotEmpty(sysUserJlcfqk.getFjcjb()),SysUserJlcfqk::getFjcjb,sysUserJlcfqk.getFjcjb());

        if (StringUtils.isNotBlank(year)){
            queryWrapper.like(SysUserJlcfqk::getFpzsj, year);
        }

        if (isSelectMe){
            CurrentUserVo currentUser = GetCurrentUserUtils.getCurrentUser();
            if (currentUser != null){
                queryWrapper.eq(StringUtils.isNotBlank(currentUser.getId()), SysUserJlcfqk::getFuserid,currentUser.getId());
            }
        }

        queryWrapper.orderByDesc(SysUserJlcfqk::getCreateTime);
        IPage<SysUserJlcfqk> pageList = sysUserJlcfqkService.page(page, queryWrapper);

        return HttpResult.ok(pageList);
    }

    @Log(title = "用户奖励惩罚情况-所有列表")
    @ApiOperation(value = "用户奖励惩罚情况-所有列表")
    @GetMapping(value = "/queryAllList")
    public HttpResult queryAllList(@RequestParam(value = "fuserid",defaultValue = "") String fuserid){

        if (StringUtils.isBlank(fuserid)){
            fuserid = GetCurrentUserUtils.getCurrentUserId();
        }
        List<SysUserJlcfqk> list = sysUserJlcfqkService.list(new LambdaQueryWrapper<SysUserJlcfqk>()
                .eq(SysUserJlcfqk::getFuserid, fuserid)
                .orderByDesc(SysUserJlcfqk::getCreateTime));

        return HttpResultVo.HttpResultList(list);
    }

    @Log(title = "用户奖励惩罚情况-添加")
    @ApiOperation(value = "用户奖励惩罚情况-添加")
    @PostMapping(value = "/addJcqk")
    public HttpResult<?> addJcqk(@RequestBody SysUserJlcfqk sysUserJlcfqk) {
        CurrentUserVo currentUser = GetCurrentUserUtils.getCurrentUser();
        if (currentUser == null){
            return HttpResult.error("登录已过期，请重新登录");
        }
        if (StringUtils.isBlank(sysUserJlcfqk.getFuserid())) {
            return HttpResult.error("用户主要参数不能为空");
        }
        sysUserJlcfqk.setId(GetUuIdUtils.ReplaceUuId());

        if (StringUtils.isBlank(sysUserJlcfqk.getFuserid())){
            sysUserJlcfqk.setFuserid(currentUser.getId());
        }
        sysUserJlcfqkService.save(sysUserJlcfqk);

        String operContent = "新增信息：";
        // 将map里面的属性和值转String
        Map<String, Object> beanMap = ObjectToMapUtils.objectToMap(sysUserJlcfqk);
        operContent += LogUtils.MapToStringMethod(beanMap);
        spcyLogService.addLogs(LogConstant.LOGS_SYS_USER_JLCFQK,operContent,sysUserJlcfqk.getId(), LogConstant.LOGS_SYS_USER_JLCFQK, SpcyConstant.LOGS_SYS_TYPE_XZ);

        HttpResult result = new HttpResult(true);
        result.setResult(sysUserJlcfqk);
        result.setMessage("添加成功");
        return result;
    }

    @Log(title = "用户奖励惩罚情况-编辑")
    @ApiOperation(value = "用户奖励惩罚情况-编辑")
    @ApiImplicitParam(name = "id",value = "用户奖励惩罚情况id",required = true)
    @PutMapping(value = "/editJcqk")
    public HttpResult<?> editJcqk(@RequestBody HashMap<String, String> buffer) throws InvocationTargetException, IllegalAccessException{
        if (StringUtils.isEmpty(buffer.get("id"))){
            return HttpResult.error("用户奖励惩罚情况id不能为空");
        }
        String djjxxxId = buffer.get("id");
        SysUserJlcfqk oldDjjbxx = sysUserJlcfqkService.getById(djjxxxId);
        if (oldDjjbxx == null){
            return HttpResult.error("当前用户奖励惩罚情况信息数据不存在，请重试");
        }
        Map<String, Object> oldMap = ObjectToMapUtils.objectToMap(oldDjjbxx);

        ConvertUtils.register(new DateConvert(), java.util.Date.class);
        // 自动完成页面到bean的数据对接
        BeanUtils.populate(oldDjjbxx, buffer);
        sysUserJlcfqkService.updateById(oldDjjbxx);

        String operContent = "基本信息修改：";
        operContent += LogUtils.BeanModifyMsg(oldDjjbxx,oldMap);

        spcyLogService.addLogs(LogConstant.LOGS_SYS_USER_JLCFQK,operContent,djjxxxId,LogConstant.LOGS_SYS_USER_JLCFQK,SpcyConstant.LOGS_SYS_TYPE_XG);
        return HttpResult.ok("修改成功");
    }

    @Log(title = "用户奖励惩罚情况-批量删除")
    @ApiOperation(value = "用户奖励惩罚情况-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public HttpResult<?> deleteBatch(@RequestParam("ids") String ids) {
        if (StringUtils.isEmpty(ids)){
            return HttpResult.error("ids参数不能为空");
        }
        List<String> idsList = Arrays.asList(ids.split(","));
        List<SysUserJlcfqk> sysUserGzjls = sysUserJlcfqkService.listByIds(idsList);
        if (CollectionUtils.isEmpty(sysUserGzjls)){
            return HttpResult.error("数据不存在，请重试");
        }
        String operContent = "";
        for (SysUserJlcfqk gzjl : sysUserGzjls){
            String id = gzjl.getId();
            sysUserJlcfqkService.removeById(id);

            operContent = "删除信息：";
            Map<String, Object> oldMap = ObjectToMapUtils.objectToMap(gzjl);
            operContent += LogUtils.MapToStringMethod(oldMap);
            spcyLogService.addLogs(LogConstant.LOGS_SYS_USER_JLCFQK,operContent,id,LogConstant.LOGS_SYS_USER_JLCFQK,SpcyConstant.LOGS_SYS_TYPE_SC);
            operContent = "";
        }

        return HttpResult.ok("删除成功");
    }

    @Log(title = "用户奖励惩罚情况-通过id查询")
    @ApiOperation(value = "用户奖励惩罚情况-通过id查询")
    @GetMapping(value = "/queryById")
    public HttpResult<?> queryById(@RequestParam("id") String id) {
        SysUserJlcfqk sysUserJlcfqk = sysUserJlcfqkService.getById(id);
        return HttpResult.ok(sysUserJlcfqk);
    }

//    @Log(title = "导入用户奖励惩罚情况基本信息数据-表格excel")
//    @ApiOperation(value = "导入用户奖励惩罚情况基本信息数据-表格excel")
//    @ApiImplicitParams(value = {
//            @ApiImplicitParam(name = "file",value = "excel模板文件",required = true)
//    })
//    @PostMapping(value = "impJlcfqkData")
    public HttpResult<?> impJlcfqkData(@RequestParam("file") MultipartFile file){
        if (file.isEmpty()){
            return HttpResult.error("文件不存在");
        }

        //获取文件名
        String fileName = file.getOriginalFilename();
        //判断文件类型，这里我们只要xls文件
        if (fileName != null && !fileName.endsWith(".xls") && !fileName.endsWith(".xlsx"))
            return HttpResult.error(1, "请选择“xls”或“xlsx”文件");

        File fileUpload = localFileUploadUtils.uploadDempFile(file,fileName);
        // 获取导入的数据
        List<Map<String, Object>> mapsList = null;
        try {
            mapsList = myExcelUtils.paresExclToMapList(BusinessConstant.IMPORT_SYS_JLCFQK_XML, fileUpload);
        } catch (Exception e) {
            log.error("导入用户奖励惩罚情况信息数据出错-{}",e.getMessage());
        }
        if (CollectionUtils.isNotEmpty(mapsList) && mapsList.size() > 0) {
            for (Map map : mapsList) {
                SysUserJlcfqk gzjl = new SysUserJlcfqk();
                BeanUtil.copyProperties(map,gzjl);
                gzjl.setId(GetUuIdUtils.ReplaceUuId());
                CurrentUserVo currentUser = GetCurrentUserUtils.getCurrentUser();
                if (currentUser == null){
                    log.error("登录过期，导入失败");
                    break;
                }
                gzjl.setFuserid(currentUser.getId());
                sysUserJlcfqkService.save(gzjl);

                String operContent = "新增导入信息：";
                Map<String, Object> bhgzMap = ObjectToMapUtils.objectToMap(gzjl);
                operContent += LogUtils.MapToStringMethod(bhgzMap);
                spcyLogService.addLogs(LogConstant.LOGS_SYS_USER_JLCFQK,operContent,gzjl.getId(),LogConstant.LOGS_SYS_USER_JLCFQK,SpcyConstant.LOGS_SYS_TYPE_XZ);
            }
        }
        fileUpload.delete();
        return HttpResult.ok("导入成功");
    }


    /*@Log(title = "下载用户奖励惩罚情况-导入模板")
    @ApiOperation(value = "下载用户奖励惩罚情况-导入模板")
    @GetMapping("/downUserJlcfqkTemplate")*/
    public void downUserJlcfqkTemplate(HttpServletResponse response){
        try {
            response.setContentType("application/ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=".concat(String.valueOf(URLEncoder.encode("userJlcfqkImpTemplate.xls", "UTF-8"))));
            OutputStream out = response.getOutputStream();
            myExcelUtils.buildImpModel(BusinessConstant.IMPORT_SYS_JLCFQK_XML, out);
        } catch (Exception e) {
            log.error("下载用户奖励惩罚情况模板错误-{}",e.getMessage());
        }
    }


    /*@Log(title = "导出用户工作经历数据-表格excel")
    @ApiOperation(value = "导出用户工作经历数据-表格excel")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "ids",value = "id字符逗号分割",dataType = "String"),
            @ApiImplicitParam(name = "fuserid",value = "用户id",required = true),
            @ApiImplicitParam(name = "year",value = "年份",dataType = "String"),
            @ApiImplicitParam(name = "isExportMe",value = "默认导出个人")
    })
    @GetMapping("/exportUserJlcfqkData")*/
    public void exportUserJlcfqkData(@RequestParam(value = "ids",defaultValue = "")String ids,
                                     SysUserJlcfqk sysUserJlcfqk,
                                     @RequestParam(value = "year",defaultValue = "")String year,
                                     @RequestParam(value = "isExportMe",defaultValue = "true")boolean isExportMe,
                                     HttpServletResponse response){
        try {
            String name = "exportUserJlcfqk";
            response.setContentType("application/ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename="
                    .concat(String.valueOf(URLEncoder.encode(name+".xls", "UTF-8"))));
            OutputStream out = response.getOutputStream();

            List<String> IdsList = Arrays.asList(ids.split(","));
            List<Object> list = new ArrayList<>(); // 导出的数据
            // 多选导出
            if (StringUtils.isNotEmpty(ids)) {
                List<SysUserJlcfqk> jlcfqkList = sysUserJlcfqkService.listByIds(IdsList);
                if (CollectionUtils.isNotEmpty(jlcfqkList)){
                    for (SysUserJlcfqk e : jlcfqkList){
                        list.add(e);
                    }
                }
            }else {
                LambdaQueryWrapper<SysUserJlcfqk> queryWrapper = new LambdaQueryWrapper<>();
                if (StringUtils.isNotBlank(sysUserJlcfqk.getFuserid())){
                    isExportMe = false;
                }
                queryWrapper.eq(StringUtils.isNotBlank(sysUserJlcfqk.getFuserid()),SysUserJlcfqk::getFuserid,sysUserJlcfqk.getFuserid());
                queryWrapper.like(StringUtils.isNotEmpty(sysUserJlcfqk.getFbjyy()), SysUserJlcfqk::getFbjyy,sysUserJlcfqk.getFbjyy());
                queryWrapper.like(StringUtils.isNotEmpty(sysUserJlcfqk.getFlx()),SysUserJlcfqk::getFlx,sysUserJlcfqk.getFlx());
                queryWrapper.like(StringUtils.isNotEmpty(sysUserJlcfqk.getFmc()),SysUserJlcfqk::getFmc,sysUserJlcfqk.getFmc());

                if (isExportMe){
                    CurrentUserVo currentUser = GetCurrentUserUtils.getCurrentUser();
                    if (currentUser != null){
                        queryWrapper.eq(StringUtils.isNotBlank(currentUser.getId()), SysUserJlcfqk::getFuserid,currentUser.getId());
                    }
                }
                queryWrapper.orderByDesc(SysUserJlcfqk::getCreateTime);
                List<SysUserJlcfqk> jlcfqkList = sysUserJlcfqkService.list(queryWrapper);
                // 条件导出
                if (CollectionUtils.isNotEmpty(jlcfqkList)){
                    for (SysUserJlcfqk e : jlcfqkList){
                        list.add(e);
                    }
                }
            }
            myExcelUtils.outputListToExclFile(BusinessConstant.IMPORT_SYS_JLCFQK_XML,list,out); // 导出模板数据成excel
        } catch (Exception e) {
            log.error("导出用户奖励惩罚情况数据出错-{}",e.getMessage());
        }
    }
}
